import sys,os,requests,json
import logging
sys.path.append(os.path.abspath('./lib'))
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED
from apscheduler.schedulers.blocking import BlockingScheduler
from api import REQUEST_VDIEO_VDIEOLIST
from config import CONFIG
from fake_useragent import UserAgent

logging.basicConfig(
    level=CONFIG['LOG_LEVEL'],
    format=CONFIG['LOG_FORMAT'],
    filemode=CONFIG['LOG_FILEMODE'],
    filename=CONFIG['LOG_FILENAME'],
    datefmt=CONFIG['LOG_DATEFORMAT'],
    )

def errorCatch(event):
    if (event.exception):
        print(event.exception)
    else:
        pass
ua = UserAgent(verify_ssl=False)
class Monitor:
    def __init__(self) -> None:
        self.maxItem = 10
        self.q = []
        self.scheduler = BlockingScheduler()
        self.scheduler.add_listener(errorCatch,EVENT_JOB_EXECUTED or EVENT_JOB_ERROR)
    def loop(self):
        self.scheduler.add_job(self.job,"interval",hours=CONFIG['BASIC_LOOPDELAY'])
#        self.scheduler.add_job(self.job, "interval", seconds=2)
        self.scheduler._logger = logging
        self.scheduler.start()
    def job(self):
        response = requests.get(REQUEST_VDIEO_VDIEOLIST + '477792',headers={
            'User-Agent': ua.random
        })
        if (response.status_code == 200):
            logging.info('Request Success')
            rawData = response.json()['data']['list']['vlist'][0:10]
            for i in rawData:
                self.q.append(
                    {
                        'description': i['description'],
                        'pic': i['pic'],
                        'title': i['title'],
                        'subtitle': i['subtitle'],
                    }
                )
            if (not os.path.exists(CONFIG['SAVE_LOCATION'])):
                os.mkdir(CONFIG['SAVE_LOCATION'])
                fs=open(CONFIG['SAVE_LOCATION'] + CONFIG['SAVE_FILENAME'],'w',encoding='utf-8')
            else:
                fs=open(CONFIG['SAVE_LOCATION'] + CONFIG['SAVE_FILENAME'],'w',encoding='utf-8')
            fs.write(json.dumps(self.q,ensure_ascii=False))
            self.q = []
            logging.info("{0} save success".format(CONFIG['SAVE_LOCATION'] + CONFIG['SAVE_FILENAME']))
            print("{0} save success".format(CONFIG['SAVE_LOCATION']))
        else:
            logging.error('Reqeust Fail')
            logging.error('Because: {0}'.format(response.status_code))
    def runNow(self):
        self.job()
m = Monitor()
m.loop()
